import json

from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.http import JsonResponse
from shopping_web import settings
from userApp.service.user.userservice import UserService
from userApp.userModel import models
from userApp.userModel.models import UserTable

userService = UserService()

def accountPage(request):
    user = json.loads(request.session['user'])
    user = userService.getUserInfo(user)
    return render(request, "account.html", {'user': user})

def user_upload_img(request):
    user = json.loads(request.session['user'])
    user = userService.getUserInfo(user)
    if request.method == 'POST':
        img = request.FILES['upload_img']
        imgname = '%s\%s' % (settings.MEDIA_ROOT, img.name)
        UserTable.objects.filter(name=user.name).update(img=img.name)
        with open(imgname, 'wb') as f:
            for fimg in img.chunks():
                f.write(fimg)
        return redirect("/user/account")
    return render(request, 'account.html', {'user': user})

